/**
 * @fileOverview 演示会话服务和 WebSocket 信道服务的使用方式
 */

// 引入 QCloud 小程序增强 SDK
var qcloud = require('../../vendor/qcloud-weapp-client-sdk/index');

// 引入配置
var config = require('../../config');
var util = require('../../utils/util');

// 显示繁忙提示
var showBusy = text => wx.showToast({
    title: text,
    icon: 'loading',
    duration: 10000
});

// 显示成功提示
var showSuccess = text => wx.showToast({
    title: text,
    icon: 'success'
});

// 显示失败提示
var showModel = (title, content) => {
    wx.hideToast();

    wx.showModal({
        title,
        content: JSON.stringify(content),
        showCancel: false
    });
};

/**
 * 使用 Page 初始化页面，具体可参考微信公众平台上的文档
 */
Page({

    /**
     * 初始数据，我们把服务地址显示在页面上
     */
    data: {
        loginUrl: config.service.loginUrl,
        requestUrl: config.service.requestUrl,
        indexUrl: config.service.indexUrl,
        dolikeUrl: config.service.dolikeUrl,
        reportMessageUrl: config.service.reportMessageUrl,
        messageList: [],
        isEmptyList: false,
        isPullRefresh: false,
        isAppending: false,
        isDataOver: false,
        currentPage: 1,
        showImages: [],
        intoView: 0,
        isShowImages: false,
        tunnelUrl: config.service.tunnelUrl,
        tunnelStatus: 'closed',
        tunnelStatusText: {
            closed: '已关闭',
            connecting: '正在连接...',
            connected: '已连接'
        }
    },
    /**
     * 
     */
    onLoad(options) {
        wx.setStorageSync('homeNeedRefresh', false);
        // 加载的时候执行登录逻辑
        this.data.messageList = new Array();
        this.doLogin();

    },
    onShow() {
        console.log("home on show");
        var homeNeedRefresh = wx.getStorageSync('homeNeedRefresh');
        if (homeNeedRefresh) {
            // do refresh
            this.getMessagesWithPage();
        } else {
           var messages = wx.getStorageSync('messages');
           if(messages&&messages.length>0 && this.data.messageList.length>0){
               this.data.messageList = messages;
               this.setData({
                   messageList:messages
               });
           }
        }
    },
    onPullDownRefresh() {
        console.log("onPullDownRefres");
        // wx.showNavigationBarLoading() //在标题栏中显示加载
        // do refresh
        this.data.isPullRefresh = true;
        this.getMessagesWithPage();
    },
    onReachBottom() {
        console.log("onReachBottom");
        // 设置底部加载更多内容的提示
        // this.data.isAppending = true;
        // this.setData({
        //     isAppending: true
        // });
    },
    hideAppendView() {
        this.data.isAppending = false;
        this.setData({
            isAppending: false
        });
    },
    scrolltolower() {
        var that = this;
        console.log("scrolltolower");

        if (that.data.isDataOver) {
            return;
        }

        // 设置底部加载更多内容的提示
        this.data.isAppending = true;
        this.setData({
            isAppending: true
        });
        // setTimeout(function () {
        //     that.hideAppendView();
        // }, 2000);
        // currentPage
        var nextPage = this.data.currentPage + 1;
        this.getMessagesWithPage(nextPage);
    },

    /**
     * 点击「登录」按钮，测试登录功能
     */
    doLogin() {
        var that = this;
        showBusy('正在登录');

        // 登录之前需要调用 qcloud.setLoginUrl() 设置登录地址，不过我们在 app.js 的入口里面已经调用过了，后面就不用再调用了
        qcloud.login({
            success(result) {
                showSuccess('登录成功');
                console.log('登录成功', result);
                showBusy('正在获取位置');
                wx.getLocation({
                    type: 'wgs84',
                    success: function (res) {
                        showSuccess('获取位置成功');
                        var latitude = res.latitude;
                        var longitude = res.longitude;
                        wx.setStorageSync('latitude', latitude);
                        wx.setStorageSync('longitude', longitude);
                    },
                    complete: function () {
                        that.doRequest();
                    }
                })
            },

            fail(error) {
                showModel('登录失败', error);
                console.log('登录失败', error);
            }
        });
    },

    /**
     * 点击「清除会话」按钮
     */
    clearSession() {
        // 清除保存在 storage 的会话信息
        qcloud.clearSession();
        showSuccess('会话已清除');
    },

    /**
     * 点击「请求」按钮，测试带会话请求的功能
     */
    doRequest() {
        var that = this;
        showBusy('更新用户数据');

        // qcloud.request() 方法和 wx.request() 方法使用是一致的，不过如果用户已经登录的情况下，会把用户的会话信息带给服务器，服务器可以跟踪用户
        qcloud.request({
            // 要请求的地址
            url: this.data.requestUrl,

            // 请求之前是否登陆，如果该项指定为 true，会在请求之前进行登录
            login: true,

            success(result) {
                showSuccess('请求成功完成');
                console.log('request success', result);
                var userInfo = result.data.data.userInfo;
                wx.setStorageSync('userInfo', userInfo);
                that.getMessagesWithPage(1);
            },
            fail(error) {
                showModel('请求失败', error);
                console.log('request fail', error);
            },
            complete() {
                console.log('request complete');
            }
        });
    },

    getMessagesWithPage(page) {
        var that = this;
        showBusy('加载数据');
        var page = page || 1;
        var latitude = wx.getStorageSync('latitude');
        var longitude = wx.getStorageSync('longitude');
        var userInfo = wx.getStorageSync('userInfo');
        var userId = userInfo.userId;
        var perNumber = 10;
        var data = { page: page, latitude: latitude, longitude: longitude, userId: userId, perNumber: perNumber };

        if (page == 1) {
            that.data.messageList = [];
            that.data.isDataOver = false;
            that.data.currentPage = 1;
        }

        qcloud.request({
            // 要请求的地址
            url: this.data.indexUrl,
            data: data,
            success(result) {

                console.log("index result：" + result);
                var resultList = result.data.result;

                if (that.data.isAppending == true) {
                    that.hideAppendView();
                    if (!resultList || resultList.length == 0) {
                        // 最后的数据，没有内容了
                        that.data.isDataOver = true;
                    } else {
                        that.data.currentPage = that.data.currentPage + 1;

                        if(resultList.length<perNumber){
                            that.data.isDataOver = true;
                        }
                    }
                }

                showSuccess('加载完成');

                if (!resultList || resultList.length == 0) {
                    // 提示用户 该附近暂无消息，赶紧作为发布第一个吃螃蟹的人吧

                } else {

                    for (let i = 0; i < resultList.length; i++) {
                        var obj = resultList[i];
                        console.log(obj.message.createdAt);
                        obj.message.time = util.formatTime(new Date(obj.message.createdAt));
                        obj.message.shotContent = util.cutStr(obj.message.content, 140);
                        obj.distance = util.formatDistance(obj.message.distance);

                        that.data.messageList.push(obj);
                    }

                    wx.setStorageSync('messages', that.data.messageList);
                }

                if (that.data.messageList.length > 0) {
                    that.setData({
                        messageList: that.data.messageList,
                        isEmptyList: false
                    });
                } else {
                    that.setData({
                        isEmptyList: true
                    });
                }
            },
            fail(error) {
                showModel('请求失败', error);
                console.log('request fail', error);
            },
            complete() {
                console.log('request complete');
                if (that.data.isPullRefresh) {
                    that.data.isPullRefresh = false;
                    // wx.hideNavigationBarLoading();
                    wx.stopPullDownRefresh();
                }

            }
        });
    },
    /**
     * 点击查看图片
     */
    showImages(e) {
        var index = e.currentTarget.dataset.index;
        var messageItem = this.data.messageList[index];
        this.data.showImages = messageItem.images;

        var that = this;

        that.setData({
            showImages: messageItem.images,
            isShowImages: true
        });
    },
    /**
     * 滚动视图
     */
    scollImagesView(e) {
        var detail = e.detail;
        // console.log("scroll detail:" + JSON.stringify(detail));
        // var width = detail.scrollWidth / 3;
        // var x = detail.scrollLeft + width / 2;
        // var intoView = x / width;
        // if (intoView > 2) {
        //     intoView = 2;
        // }
        // this.setData({ intoView: intoView });

    },
    /**
     * 关闭查看图片
     */
    closeShowView() {
        var that = this;
        that.setData({
            isShowImages: false
        });
    },
    /**
     * 点击捐赠按钮
     */
    goDonatePage(e) {
        var messageid = e.currentTarget.dataset.messageid;
        var userid = e.currentTarget.dataset.userid;
        var username = e.currentTarget.dataset.username;
        var avatarurl = e.currentTarget.dataset.avatarurl;
        var donateUrl = '../donate/index?messageid=' + messageid + '&userid=' + userid + '&username=' + username + '&avatarurl=' + avatarurl;
        wx.navigateTo({ url: donateUrl });
    },
    /**
     * 点击支持
     */
    doSupport(e) {
        var that = this;
        // showBusy('点赞...');
        var messageid = e.currentTarget.dataset.messageid;
        var enablelike = e.currentTarget.dataset.enablelike

        var like = 1;
        if (enablelike == 0) {
            enablelike = 1;
            like = 0;
        } else {
            enablelike = 0;
        }

        var userInfo = wx.getStorageSync('userInfo');
        var userId = userInfo.userId;
        // 请求服务端，支持当前的请求
        var data = {
            messageId: messageid,
            userId: userId,
            like: like
        };

        qcloud.request({
            // 要请求的地址
            url: this.data.dolikeUrl,
            data: data,
            method: 'POST',
            success(result) {
                // showSuccess('请求成功完成');
                var result = result.data.result;
                // data.result.likeCount | messageid

                for (let i = 0; i < that.data.messageList.length; i++) {
                    let indexObj = that.data.messageList[i];
                    if (indexObj.message.id == result.messageId) {
                        indexObj.message.likes = result.likeCount;
                        indexObj.enableLike = enablelike;
                    }
                }

                var messages = wx.getStorageSync('messages');
                for(let i=0; i<messages.length; i++){
                    var item = messages[i];
                    if(item.id = result.messageId){
                        item.message.likes = result.likeCount;
                        item.enableLike = enablelike;
                        break;
                    }
                }
                wx.setStorageSync('messages', messages);

                that.setData({
                    messageList: that.data.messageList
                });
            },
            fail(error) {
                showModel('请求失败', error);
                console.log('request fail', error);
            },
            complete() {
                console.log('request complete');
            }
        });
    },

    /**
     * 评论
     */
    doComment(e) {
        var messageid = e.currentTarget.dataset.messageid;
        this.openDetail(messageid);
    },
    switchTunnel(e) {
        const turnedOn = e.detail.value;

        if (turnedOn && this.data.tunnelStatus == 'closed') {
            this.openTunnel();

        } else if (!turnedOn && this.data.tunnelStatus == 'connected') {
            this.closeTunnel();
        }
    },

    /**
     * 点击「打开信道」，测试 WebSocket 信道服务
     */
    openTunnel() {
        // 创建信道，需要给定后台服务地址
        var tunnel = this.tunnel = new qcloud.Tunnel(this.data.tunnelUrl);

        // 监听信道内置消息，包括 connect/close/reconnecting/reconnect/error
        tunnel.on('connect', () => {
            console.log('WebSocket 信道已连接');
            this.setData({ tunnelStatus: 'connected' });
        });

        tunnel.on('close', () => {
            console.log('WebSocket 信道已断开');
            this.setData({ tunnelStatus: 'closed' });
        });

        tunnel.on('reconnecting', () => {
            console.log('WebSocket 信道正在重连...')
            showBusy('正在重连');
        });

        tunnel.on('reconnect', () => {
            console.log('WebSocket 信道重连成功')
            showSuccess('重连成功');
        });

        tunnel.on('error', error => {
            showModel('信道发生错误', error);
            console.error('信道发生错误：', error);
        });

        // 监听自定义消息（服务器进行推送）
        tunnel.on('speak', speak => {
            showModel('信道消息', speak);
            console.log('收到说话消息：', speak);
        });

        // 打开信道
        tunnel.open();

        this.setData({ tunnelStatus: 'connecting' });
    },

    /**
     * 点击「发送消息」按钮，测试使用信道发送消息
     */
    sendMessage() {
        // 使用 tunnel.isActive() 来检测当前信道是否处于可用状态
        if (this.tunnel && this.tunnel.isActive()) {
            // 使用信道给服务器推送「speak」消息
            this.tunnel.emit('speak', {
                'word': 'I say something at ' + new Date(),
            });
        }
    },

    /**
     * 点击「测试重连」按钮，测试重连
     * 也可以断开网络一段时间之后再连接，测试重连能力
     */
    testReconnect() {
        // 不通过 SDK 关闭连接，而是直接用微信断开来模拟连接断开的情况下，考察 SDK 自动重连的能力
        wx.closeSocket();
    },

    /**
     * 点击「关闭信道」按钮，关闭已经打开的信道
     */
    closeTunnel() {
        if (this.tunnel) {
            this.tunnel.close();
        }

        this.setData({ tunnelStatus: 'closed' });
    },

    /**
     * 点击「聊天室」按钮，跳转到聊天室综合 Demo 的页面
     */
    openChat() {
        // 微信只允许一个信道再运行，聊天室使用信道前，我们先把当前的关闭
        this.closeTunnel();
        wx.navigateTo({ url: '../chat/chat' });
    },
    doSubmitMessage() {
        wx.navigateTo({ url: '../message/add' });
    },
    openMessage(e) {
        var messageid = e.currentTarget.dataset.messageid;
        this.openDetail(messageid);
    },
    openDetail(messageId) {
        var detailUrl = "../message/index?messageid=" + messageId;
        wx.navigateTo({ url: detailUrl });
    },
    doReport(e) {
        var that = this;
        var messageid = e.currentTarget.dataset.messageid;
        var userid = e.currentTarget.dataset.userid;

        wx.showModal({
            title: '举报',
            content: '该动态存内容不合法，我要举报！',
            success: function (res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                    showBusy('正在处理');
                    var data = { messageId: messageid, userId: userid }
                    // 
                    qcloud.request({
                        // 要请求的地址
                        url: that.data.reportMessageUrl,
                        data: data,
                        method: 'POST',
                        success(result) {
                            // showSuccess('请求成功完成');
                            var result = result.data.result;
                            // data.result.likeCount | messageid
                            showSuccess('举报成功');
                            
                        },
                        fail(error) {
                            showModel('请求失败', error);
                            console.log('request fail', error);
                        },
                        complete() {
                            console.log('request complete');
                        }
                    });
                }
            }
        })

    }
});
